<template>
  <div>
    <div class="table-box" v-if="!UserCourseProtableVisible">
      <!-- 必须设置row-key="course_id"，否则拖动后的顺序会出错 -->
      <ProTable
        ref="userListProtable"
        title="用户列表"
        :columns="user_list_columns"
        :request-api="getUserTableList"
        :pagination="false"
        row-key="user_id"
        @row-click="rowClick"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected"> 批量封禁 </el-button>
        </template>
        <!-- Expand -->
        <template #expand="scope">
          {{ scope.row }}
        </template>
        <!-- usernameHeader -->
        <template #usernameHeader="scope">
          <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
            {{ scope.column.label }}
          </el-button>
        </template>
        <!-- createTime -->
        <template #createTime="scope">
          <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
            {{ scope.row.createTime }}
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="View" @click="openUserInfoDrawer('查看', scope.row)"> 查看 </el-button>
          <el-button type="primary" link :icon="EditPen" @click="openUserInfoDrawer('编辑', scope.row)"> 编辑 </el-button>
          <el-button type="primary" link :icon="Delete" @click="delUser(scope.row)"> 删除 </el-button>
        </template>
      </ProTable>
      <EditUserInfoDrawer ref="editUserInfoDrawerRef" />
      <ImportExcel ref="dialogRef" />
    </div>
    <div class="table-box" v-if="UserCourseProtableVisible">
      <!-- 必须设置row-key="course_id"，否则拖动后的顺序会出错 -->
      <ProTable
        ref="userCourseProtable"
        title="用户列表"
        :columns="user_course_list_columns"
        :request-api="getUserCourseTableList"
        :pagination="false"
        row-key="course_id"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="primary" :icon="Back" plain @click="UserCourseProtableVisible = false"> 回到用户管理 </el-button>
          <el-button type="primary" :icon="CirclePlus" @click="openEditUserCourseDrawer('新增')"> 给用户新增科目 </el-button>
          <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected"> 批量删除 </el-button>
        </template>
        <!-- Expand -->
        <template #expand="scope">
          {{ scope.row }}
        </template>
        <!-- usernameHeader -->
        <template #usernameHeader="scope">
          <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
            {{ scope.column.label }}
          </el-button>
        </template>
        <!-- createTime -->
        <template #createTime="scope">
          <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
            {{ scope.row.createTime }}
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="Delete" @click="delUserCourse(scope.row)"> 删除 </el-button>
        </template>
      </ProTable>
      <EditUserCourseDrawer ref="editUserCourseDrawerRef" />
    </div>
  </div>
</template>

<script setup lang="tsx" name="courseManage">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Refresh, Back } from "@element-plus/icons-vue";
import { addCourseApi, deleteCourseApi, getCourseListApi, sortCourseApi, updateCourseApi } from "@/api/modules/course";
import EditCourseDrawer from "@/views/admin/course_manage/editCourseDrawer.vue";
import { TableColumnCtx } from "element-plus/es/components/table/src/table-column/defaults";
import { Course } from "@/api/interface";
import { deleteUserApi, getUserList } from "@/api/modules/user";
import { addUserCourseApi, deleteUserCourseApi, getUserCourseListApi, updateUserCourseApi } from "@/api/modules/user_course";
import EditUserCourseDrawer from "@/views/admin/user_manage/editUserCourseDrawer.vue";
import EditUserInfoDrawer from "@/views/admin/user_manage/editUserInfoDrawer.vue";
import UserDrawer from "@/views/proTable/components/UserDrawer.vue";

const router = useRouter();
const paths = router.currentRoute.value.path.split("/");
const course_id = paths[paths.length - 1];
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const userListProtable = ref<ProTableInstance>();
const userCourseProtable = ref<ProTableInstance>();
const editUserInfoDrawerRef = ref<InstanceType<typeof EditUserInfoDrawer>>();
const selectUserId = ref<string>("");
const UserCourseProtableVisible = ref<boolean>(false);
const getUserTableList = async () => {
  let result = await getUserList({});
  return result;
};

const getUserCourseTableList = async () => {
  let result: any = await getUserCourseListApi({ user_id: selectUserId.value });
  let course_arr = [];
  for (let course of result?.data) {
    if (course.parent_id !== null) {
      course_arr.push(course);
    }
  }
  result.data = course_arr;
  return result;
};

// 单击行
const rowClick = (row: any, column: TableColumnCtx<any>) => {
  if (column.property == "radio" || column.property == "operation") return;
  selectUserId.value = row.user_id;
  userCourseProtable.value?.getTableList();
  UserCourseProtableVisible.value = true;
};

// 表格配置项
const user_list_columns: ColumnProps<any>[] = [
  { prop: "user_id", label: "编号", minWidth: 20 },
  { prop: "nick", label: "昵称", minWidth: 20 },
  { prop: "role", label: "角色", minWidth: 50 },
  { prop: "operation", label: "操作", fixed: "right", minWidth: 20 }
];

const user_course_list_columns: ColumnProps<any>[] = [
  { prop: "parent_title", label: "父级科目", minWidth: 20 },
  { prop: "title", label: "科目", minWidth: 20 },
  { prop: "introduce", label: "科目简介", minWidth: 20 },
  { prop: "operation", label: "操作", fixed: "right", minWidth: 20 }
];
const delUser = async (row: any) => {
  let params = {
    user_id: row.user_id
  };
  await useHandleData(deleteUserApi, params, `删除用户`);
  userListProtable.value?.getTableList();
};

const delUserCourse = async (row: any) => {
  let params = {
    user_id: selectUserId.value,
    course_id: row.course_id
  };
  console.log("row : " + JSON.stringify(course_id));
  await useHandleData(deleteUserCourseApi, params, `收回科目`);
  userCourseProtable.value?.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const editUserCourseDrawerRef = ref<InstanceType<typeof EditUserCourseDrawer> | null>(null);
const openEditUserCourseDrawer = (title: string, row: Partial<any> = {}) => {
  if (title === "新增") {
    row = { order_number: row.order_number };
  }
  const params = {
    title,
    isView: false,
    row: { ...row },
    api: title === "新增" ? addUserCourseApi : title === "编辑" ? updateUserCourseApi : undefined,
    getTableList: userCourseProtable.value?.getTableList,
    // getTableList: getTableList,
    user_id: selectUserId.value
  };
  editUserCourseDrawerRef.value?.acceptParams(params);
};

const openUserInfoDrawer = (title: string, row: Partial<any> = {}) => {
  if (title === "新增") {
    row = { course_id: row.course_id, order_number: row.order_number };
  }
  const params = {
    title,
    isView: false,
    row: { ...row },
    api: title === "新增" ? addCourseApi : title === "编辑" ? updateCourseApi : undefined,
    getTableList: userListProtable.value?.getTableList,
    // getTableList: getTableList,
    course_id: course_id,
    order_number: row.order_number ?? "",
    user_id: selectUserId.value
  };
  editUserInfoDrawerRef.value?.acceptParams(params);
};
</script>
